package club.janna.springboot.study.config;

import club.janna.springboot.study.interceptor.JannaLimiterInterceptor;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.sql.DataSource;

@Configuration
public class MyWebMvcConfiguration extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JannaLimiterInterceptor());
    }

    @Bean
    @ConfigurationProperties("datasource-master")
    public DataSource masterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("datasource-slave1")
    public DataSource slaveDataSource1() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("datasource-slave2")
    public DataSource slaveDataSource2() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public JannaReadWriteDataSource dataSource(@Qualifier("masterDataSource") DataSource master,
                                               @Qualifier("slaveDataSource1") DataSource slave1,
                                               @Qualifier("slaveDataSource2") DataSource slave2) {
        return new JannaReadWriteDataSource(new DataSource[]{master}, slave1, slave2);
    }
}
